﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Forms.Rapor;
using ConfExpert.Forms.SatinAlma;
using ConfExpert.Forms.Siparisler;
using ConfExpert.Properties;
using ConfExpert.Utility;

using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.BandedGrid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using DevExpress.XtraTab;
using DevExpress.XtraTab.ViewInfo;
using DevExpress.XtraVerticalGrid.Events;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

//ozet sp'si bütün siparişleri getirmese (sadece açıklar seçildiği zaman + OK)

namespace ConfExpert.Forms.Satinalma
{
    public partial class KSip : XForm
    {
        int _SezonId;
        bool KDept = false;
        string SipNo, _OrderRef, Kapsam = "Bütün siparişler";
        string[] Expl = new string[10];
        string[] warnings = "Gelmesine 2 haftadan az kalan- ;Geç kalan- ;Tolerans dışı veya eksik gelen- ;Yanlış fiyat veya şartla gelen- ;Fatura bekleyen- ".Split(';');
        int _BrandId, _UreticiId, _SipVerenId, Max = 100, SipVerenId = 0;
        int[] warningsCnt = new int[16];
        bool isHandleDestroyed = false;
        BindingSource bsKST, bsKSTpvt, bsLayouts;
        DateTime StartDate = DateTime.Now.AddDays(-120), _ETA;
        Color posColor = Color.YellowGreen, negColor = Color.OrangeRed;
        Color[] colors;
        //static System.Timers.Timer timerD = null;
        delegate void UpdateDataSourceDelegate();

        enum pages
        {
            Ozet = 0,
            DetayListe,
            Raporlama,
            AyrimTablosu
        }

        public KSip()
        {
            InitializeComponent();
        }

        void KST_Load(object sender, EventArgs e)
        {
            bool YetkiEditArsivMt = ytk(72);    // (new List<int> { 11, 14, 17, 23, 85, 89, 103, 112, 116 }).Contains(WhoAmI);
            bool YetkiEditArsivKontrol = ytk(70);

            KDept = (ytk(164) || isAdmin);   //AliÖ.
            btnSatirEkle.Visible = KDept;
            btnYukleme.Enabled = false;
            PrepareRiKapsam();
            tabAna.SelectedTabPage = tpListe;
            tabAna.ShowTabHeader = DefaultBoolean.False;

            btnKaydet.Text = "&Kaydet ve Güncelle";
            btnKaydet.Click += btnKaydet_Click;

            dtY = new DataTable("Y");
            dtY.Columns.Add("idx", typeof(int));
            dtY.Columns.Add("SonYukleme", typeof(decimal));
            dtY.Columns.Add("BolunecekMt", typeof(decimal));

            //dtAyrim.AddAutoIncrementalColumn("idx");
            //dtAyrim.SetPK("idx");

            //timerD = new System.Timers.Timer(6000000);

            //Session.StartWatcher("1");

            IntPtr handle = this.Handle; // Forces creation of the handle

            //tabAna.ShowTabHeader = DefaultBoolean.False;

            btnGetir.Click += new EventHandler(btnGetir_Click);
            btnTemizle.Click += new EventHandler(btnTemizle_Click);

            CreateVerticalGrid();

            bgw.DoWork += new System.ComponentModel.DoWorkEventHandler(bgw_DoWork);
            bgw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);

            //MyRefreshX();

            //timerD.SynchronizingObject = this;  // pivot;
            //timerD.Elapsed += new System.Timers.ElapsedEventHandler(RaiseUpdate);
            //timerD.Enabled = true;  // WhoAmI != 82 && WhoAmI != 84;
            //MyRefresh();
            //timerD.AutoReset = true;

            this.FormClosing += new FormClosingEventHandler(KSip_FormClosing);
            TAM.KSTTableAdapter = new Datasets.MyDataTableAdapters.KSTTableAdapter();

            this.Text = "KST";
            Upd(pages.Ozet, "- KST");
            Upd(pages.Raporlama, "- KST");
            Upd(pages.DetayListe, "- KST");

            //TODO: Esti hanımın tüm siparişleri görmesi lazım. Halbuki V_SalesPerson a dahil olduğu için diğer MT ler gibi sadece kendi siparişlerini görüyor.
            if (!ds.KST.Columns.Contains("SonYukleme"))
                ds.KST.Columns.Add("SonYukleme", typeof(decimal));
            if (!ds.KST.Columns.Contains("BolunecekMt"))
                ds.KST.Columns.Add("BolunecekMt", typeof(decimal));
            if (!ds.KST.Columns.Contains("KalanMt"))
                ds.KST.Columns.Add("KalanMt", typeof(decimal));
            if (!ds.KST.Columns.Contains("LineTotal"))
                ds.KST.Columns.Add("LineTotal", typeof(decimal));
            if (!ds.KST.Columns.Contains("EstTotal"))
                ds.KST.Columns.Add("EstTotal", typeof(decimal));
            if (!ds.KST.Columns.Contains("Yukleme"))
                ds.KST.Columns.Add("Yukleme", typeof(int));
            if (!ds.KST.Columns.Contains("Varis"))
                ds.KST.Columns.Add("Varis", typeof(int));
            if (!ds.KST.Columns.Contains("Seç"))
                ds.KST.Columns.Add("Seç", typeof(bool));

            Exp(true);

            bsKST = new BindingSource(ds, "KST");
            bsKSTpvt = new BindingSource(ds, "KST");

            AddBsToList(bsKST);

            //Session.StartWatcher("2");

            InitGridView(bgvKst, bsKST);

            //bgvKst.MakeColumnsReadOnly("YuklenenMt");

            if (!KDept)
                bgvKst.MakeReadOnly("YikamaRecetesi");





            bgvKst.OptionsFilter.ShowAllTableValuesInFilterPopup = false;
            bgvKst.OptionsFilter.ShowAllTableValuesInCheckedFilterPopup = false;

            bgvKst.FormatAsNumber(1, "Mt", "YuklenenMt", "SonYukleme", "BolunecekMt", "DepoyaGelenMt", "KalanMt");
            bgvKst.AddSummary("Mt", "YuklenenMt", "SonYukleme", "BolunecekMt", "DepoyaGelenMt", "KalanMt", "LineTotal", "EstTotal");

            bgvKst.MakeColumnInvisible("SipNo", "xMiktarOnay", "xFiyatOnay", "YuklemeId");
            bgvKst.SetCaptions("SipNo2:PO#", "KstCategoryId:Kategori1", "KstCategory2Id:Kategori2");

            //deStart.EditValueChanged += new EventHandler(chkAktif_CheckedChanged)

            //Session.StartWatcher("3");

            //bgvKst.OptionsView.RowAutoHeight = false;

            int cnt = 0;
            bgvKst.Images = bgvIcons;
            string[] parts = "REFERANS;SİPARİŞ BİLGİLERİ;NOTLAR & HL;Satinalma / TERMİN BİLGİLERİ;DEPO GİRİŞ / KAYIT".Split(';');
            string[] starts = "idx;Durum1Id;Notlar;GomlekTermini;FatBekliyor;".Split(';');

            for (int i = 0; i < parts.Length; i++)
            {
                GridBand gb = new DevExpress.XtraGrid.Views.BandedGrid.GridBand();
                gb.Caption = "<b>" + parts[i] + "</b>";
                gb.ImageIndex = i;
                gb.Name = "gb" + gb.ImageIndex.ToString();
                //TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gb.OptionsBand.AllowHotTrack = true;
                bgvKst.Bands.Add(gb);

                for (int i2 = cnt; i2 < bgvKst.Columns.Count; i2++)
                {
                    if (bgvKst.Columns[cnt].FieldName == starts[i + 1] && cnt > 0)
                        break;

                    bgvKst.Bands[i].Columns.Add(bgvKst.Columns[cnt]);

                    if (bgvKst.Columns[cnt].FieldName == "Scan")
                        bgvKst.Columns["Scan"].OwnerBand = bgvKst.Bands[0];

                    cnt++;
                }
            }

            if (YetkiEditArsivMt)
            {
                bgvKst.Columns["Seç"].OwnerBand = bgvKst.Bands[0];
                bgvKst.Columns["Seç"].ColVIndex = bgvKst.Columns["ArsivMt"].ColVIndex;
            }
            else
                bgvKst.Columns["Seç"].ColVIndex = -1;

            bgvKst.Columns["SonYukleme"].OwnerBand = bgvKst.Bands[0];
            bgvKst.Columns["SonYukleme"].ColVIndex = -1;

            bgvKst.Columns["BolunecekMt"].OwnerBand = bgvKst.Bands[0];
            bgvKst.Columns["BolunecekMt"].ColVIndex = -1;

            bgvKst.OptionsView.AllowHtmlDrawHeaders = true;
            bgvKst.Columns["Scan"].ColVIndex = bgvKst.Columns["PRO"].ColVIndex;

            //Session.StartWatcher("4");

            //ds.KST.Columns["LineTotal"].Expression = "DepoyaGelenMt * FaturaFiyati";
            bgvKst.FormatAsNumber(2, "LineTotal");
            bgvKst.Columns["LineTotal"].ColVIndex = 8;   // bgvKst.Columns["FaturaDvzId"].VisibleIndex;

            bgvKst.FormatAsNumber(2, "EstTotal", "AnlasilanFiyat");
            bgvKst.Columns["EstTotal"].OwnerBand = bgvKst.Columns["OngTeslimSekliId"].OwnerBand;
            bgvKst.Columns["EstTotal"].ColVIndex = bgvKst.Columns["OngTeslimSekliId"].ColVIndex + 1;

            bgvKst.Columns["Yukleme"].OwnerBand = bgvKst.Columns["Varis"].OwnerBand = bgvKst.Bands[3];
            bgvKst.Columns["Yukleme"].ColVIndex = bgvKst.Columns["YuklemeTarihi"].ColVIndex + 1;
            bgvKst.Columns["Varis"].ColVIndex = bgvKst.Columns["ETAVarisTarihi"].ColVIndex + 1;
            bgvKst.Columns["MusteriKodu"].ColVIndex = bgvKst.Columns["SipVerenId"].ColVIndex + 1;




            bgvKst.GridControl.MenuManager = barManager;
            //YENİ SÜRÜMDE ÇALIŞMADI!
            //PrepareImageComboBoxEdit(gvKstOzet, "KumasTerminDurumu", "4 HAFTADAN FAZLA VAR|2 HAFTADAN FAZLA VAR|2 HAFTADAN AZ KALDI!|DİKKAT KUMAŞ GECİKTİ!");
            bgvKst.CellMerge += new CellMergeEventHandler(gv2_CellMerge);

            foreach (string str in "UreticiId;BrandId".Split(';'))
                bgvKst.Columns[str].OptionsFilter.FilterPopupMode = FilterPopupMode.CheckedList;

            bgvKst.ShowFilterPopupCheckedListBox += new FilterPopupCheckedListBoxEventHandler(gv_ShowFilterPopupCheckedListBox);
            CenterGridColumn(bgvKst.Columns["Tip"]);

            //Session.StartWatcher("5");

            colors = new Color[]{
                Color.FromArgb(220, 232, 162),
                Color.FromArgb(238, 243, 213),
                Color.Gainsboro,
                Color.LightGray,
                Color.AntiqueWhite,
                Color.FromArgb(220, 232, 162),
                Color.FromArgb(238, 243, 213)
            };

            bgvKst.OptionsView.EnableAppearanceEvenRow = false;
            bgvKst.RowCellStyle += new RowCellStyleEventHandler(bgvKST_RowCellStyle);
            bgvKst.RowStyle += new RowStyleEventHandler(bgvKst_RowStyle);
            bgvKst.BestFitMaxRowCount = 50;

            bsLayouts = new BindingSource(ds, "SavedLayouts");
            leLayout.Properties.DataSource = bsLayouts;
            leLayout.Properties.DisplayMember = leLayout.Properties.ValueMember = "LayoutName";
            leLayout.Properties.PopulateColumns();

            leLayout.Properties.Columns.Clear();
            leLayout.Properties.Columns.Add(new LookUpColumnInfo("LayoutName", "LayoutName", -1));
            leLayout.Properties.PopupWidth = 120;

            leLayout.Properties.NullText = "";
            leLayout.Properties.TextEditStyle = TextEditStyles.Standard;
            leLayout.Properties.SortColumnIndex = 0;

            //Session.StartWatcher("6");

            tabAna.SelectedPageChanged += new DevExpress.XtraTab.TabPageChangedEventHandler(tabAna_SelectedPageChanged);
            this.HandleDestroyed += new EventHandler(KST_HandleDestroyed);
            bgvKst.SelectionChanged += new DevExpress.Data.SelectionChangedEventHandler(bgvKST_SelectionChanged);
            bgvKst.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.None;

            barManager.ForceLinkCreate();
            barManager.ItemClick += new ItemClickEventHandler(barManager_ItemClick);

            PopupMenu popKapsam = new PopupMenu(barManager);
            popKapsam.Name = "Actions";
            foreach (string str in "Çağrılan satır;O markaya ait satırlar;O üreticiye ait satırlar;Siparişin tamamı;Bütün siparişler".Split(';'))
            {
                BarButtonItem bbi = new BarButtonItem(barManager, str, 0, BarShortcut.Empty);
                bbi.Name = str;
                bbi.GroupIndex = 1;
                //bbi.AllowAllUp = true;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
                popKapsam.AddItems(new BarItem[] { bbi });
            }
            ddbKapsam.DropDownControl = popKapsam;

            PopupMenu popBrands = new PopupMenu(barManager);
            popBrands.Name = "Hızlı Geçiş";
            cnt = 0;
            foreach (string str in ("TÜMÜ;" + String.Join(";", parts)).Split(';'))
            {

                BarButtonItem bbi = new BarButtonItem(barManager, str, 0, BarShortcut.Empty);
                bbi.Tag = cnt++;

                bbi.GroupIndex = 2;
                //bbi.AllowAllUp = true;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;

                popBrands.AddItems(new BarItem[] { bbi });
                if (cnt > 6)
                    break;
            }
            ddbBands.DropDownControl = popBrands;

            //((RepositoryItemLookUpEdit)bgvKST.Columns["UreticiId"].ColumnEdit).TextEditStyle = TextEditStyles.Standard;
            //gvKstOzet.ActiveFilterString = "SipVerenId = " + Session.CurrentUser.UserName; // +" AND SipDurumu1Id = 1";

            //1: KST formu
            //0: KST sipariş satırları update+insert
            //1: yeni sipariş no. almak
            //2: özet sayfasında kendi değil herkesin siparişini görmek            

            bgvKst.Columns["ArsivMt"].Visible = bgvKst.Columns["ArsivKontrol"].Visible = YetkiEditArsivMt | YetkiEditArsivKontrol;
            bgvKst.Columns["ArsivMt"].OptionsColumn.AllowEdit = YetkiEditArsivMt;
            bgvKst.Columns["ArsivKontrol"].OptionsColumn.AllowEdit = YetkiEditArsivKontrol;

            InitPivot(pgcRapor);
            InitPivot(pgcAyrim);

            PivotGridField fldx = pgcAyrim.Fields.Add("KalanMt", PivotArea.DataArea);
            //fldx.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            fldx.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            fldx.CellFormat.FormatString = "#,###.##";
            //pgcAyrim.CustomUnboundFieldData += new CustomFieldDataEventHandler(pgc_CustomUnboundFieldData);

            leLayout.EditValueChanged += new EventHandler(leLayout_EditValueChanged);
            teLayout.EditValueChanged += new EventHandler(teLayout_EditValueChanged);

            //Session.StartWatcher("7");

            //AppSession.MainForm.ShowProgress();
            //AppSession.MainForm.HideProgress();

            //Session.StartWatcher("8");

            //bgvKst.Columns["KompozisyonId"].ColumnEdit = RI(Rp.Kompozisyon);
            //bgvKst.CustomDrawCell += new RowCellCustomDrawEventHandler(bgvKst_CustomDrawCell);
            gleSiparis.EditValueChanged += new EventHandler(gleSiparis_EditValueChanged);

            pgcAyrim.OptionsView.ShowGrandTotalsForSingleValues = true;
            pgcAyrim.OptionsView.ShowColumnGrandTotals = true;
            pgcAyrim.OptionsView.ShowRowGrandTotals = true;
            pgcAyrim.OptionsView.ShowRowTotals = false;
            pgcAyrim.CellSelectionChanged += new EventHandler(pgcAyrim_CellSelectionChanged);

            btnSatirEkle.Click += new EventHandler(btnSatirEkle_Click);
            tabAna.DoubleClick += new EventHandler(TabControl_DoubleClick);

            //Session.StartWatcher("9");

            DrillDownGrid((GridView)gridControl1.MainView, bsKSTpvt);
            DrillDownGrid((GridView)gridControl2.MainView, bsKSTpvt);

            //Session.StartWatcher("10");

            btnYukleme.CheckedChanged += btnYukleme_CheckedChanged;
            btnSatirBol.CheckedChanged += btnSatirBol_CheckedChanged;

            bgvKst.OptionsBehavior.EditorShowMode = AppSession.Settings.EditorShowMode; // .Checked ? DevExpress.Utils.EditorShowMode.MouseDown : DevExpress.Utils.EditorShowMode.Default;   //checkbox hemen seçilebilsin diye!

            GridManager gmArt = GridManager.GetManager(bgvKst);
            gmArt.GridMenu.AddMenu("Artikel Ekle/Değiştir", KSip_DoubleClick);
            gmArt.GridMenu.AddMenu("Kod Sihirbazı", KartAra_Click, Resources.wizardcontrol);

            //if (RibbonManager.Admins.Contains(WhoAmI))
            //    gmArt.GridMenu.AddMenu("Ayrım Sepetine Ekle", AyrimSihirbazi_Click, Resources.process_24);

            gmArt.GridMenu.AddMenu("StokKodu'nu ÜreticiKodu olarak belirle", SKToUK_Click);
            gmArt.GridMenu.AddMenu("StokKodu'nu MüşteriKodu olarak belirle", SKToMK_Click);
            gmArt.GridMenu.AddMenu("Kartın Üretici/Müşteri kodları", UKMK, null);

            gmArt.GridMenu.AddMenu("Özellikleri ve MK'yı stok kartına TAŞI", Sync, null, true);

            foreach (string str in "xTerminAciklama;xMiktarAciklama;xFiyatAciklama".Split(';'))
                bgvKst.Columns[str].ColumnEdit = new RepositoryItemMemoEdit();

            btnYazdir.Click += new EventHandler(btnYazdir_Click);
            btnSaveLayout.Click += new EventHandler(btnSaveLayout_Click);
            btnDeleteLayout.Click += new EventHandler(btnDeleteLayout_Click);

            RefreshFilter();

            //bgvKst.ShowFindPanel();
            //gvKstOzet.ShowFindPanel();
            bgvKst.ShowingEditor += new System.ComponentModel.CancelEventHandler(bgvKst_ShowingEditor);
            //Session.StopWatcher();

            FillAyrimTables();

            bgvKst.CellValueChanged += bgvKst_CellValueChanged;
        }

        void btnYukleme_CheckedChanged(object sender, EventArgs e)
        {
            if (btnYukleme.Checked)
                btnSatirBol.Checked = false;

            bgvKst.Columns["SonYukleme"].ColVIndex = btnYukleme.Checked ? bgvKst.Columns["YuklenenMt"].ColVIndex + 1 : -1;

            if (!btnYukleme.Checked)
                foreach (DataRow dr in ds.KST.Rows)
                    if (dr["SonYukleme"] != DBNull.Value)
                        dr["SonYukleme"] = DBNull.Value;
        }

        void btnSatirBol_CheckedChanged(object sender, EventArgs e)
        {
            if (btnSatirBol.Checked)
                btnYukleme.Checked = false;

            bgvKst.Columns["BolunecekMt"].ColVIndex = btnSatirBol.Checked ? bgvKst.Columns["YuklenenMt"].ColVIndex + 1 : -1;

            if (!btnSatirBol.Checked)
                foreach (DataRow dr in ds.KST.Rows)
                    if (dr["BolunecekMt"] != DBNull.Value)
                        dr["BolunecekMt"] = DBNull.Value;
        }

        void bgvKst_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName != "KaliteId") return;

            int KaliteId = e.Value.ToInt();
            MyData.KaliteRow r = AppSession.Lookups.Kalite.FindByKaliteId(KaliteId);
            if (r != null)
            {
                string val = bgvKst.GetFocusedRowCellDisplayText("KompozisyonId") +
                    bgvKst.GetFocusedRowCellDisplayText("Konstruksiyon") +
                    bgvKst.GetFocusedRowCellDisplayText("EnGrubu") +
                    bgvKst.GetFocusedRowCellDisplayText("Agirlik_GrM2") +
                    bgvKst.GetFocusedRowCellDisplayText("FinishId");

                bool cfm = false;
                if (val == string.Empty)
                    cfm = true;
                else
                    cfm = (XtraMessageBox.Show("Seçtiğiniz kalitenin, bu satırın teknik özelliklerini OVERWRITE etmesini onaylıyor musunuz?", "Teyid", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes);

                if (cfm)
                {
                    if (!r.IsKompozisyonIdNull())
                        bgvKst.SetFocusedRowCellValue("KompozisyonId", r.KompozisyonId);
                    else
                        bgvKst.SetFocusedRowCellValue("KompozisyonId", null);

                    if (!r.IsKonstruksiyonNull())
                        bgvKst.SetFocusedRowCellValue("Konstruksiyon", r.Konstruksiyon);
                    else
                        bgvKst.SetFocusedRowCellValue("Konstruksiyon", null);

                    if (!r.IsEnGrubuNull())
                        bgvKst.SetFocusedRowCellValue("EnGrubu", r.EnGrubu);
                    else
                        bgvKst.SetFocusedRowCellValue("EnGrubu", null);

                    if (!r.IsAgirlikNull())
                        bgvKst.SetFocusedRowCellValue("Agirlik_GrM2", r.Agirlik);
                    else
                        bgvKst.SetFocusedRowCellValue("Agirlik_GrM2", null);

                    if (!r.IsFinishIdNull())
                        bgvKst.SetFocusedRowCellValue("FinishId", r.FinishId);
                    else
                        bgvKst.SetFocusedRowCellValue("FinishId", null);

                    //bgvKst.SetFocusedRowCellValue("KaliteId", KaliteId);

                }

            }

        }


        private void Sync(object sender, EventArgs e)
        {
            using (SyncKart ke = new SyncKart(GetIdxs()))
                ke.ShowDialog();
        }

        private string GetProductIds()
        {
            string ids = "";
            foreach (int rowHandle in bgvKst.GetSelectedRows())
            {
                if (rowHandle > -1)
                {
                    string pId = bgvKst.GetRowCellValue(rowHandle, "ProductId").ToString();

                    if (pId != "")
                        ids += pId + ",";
                }
            }

            ids = ids.RemoveIfEndsWith(",");

            return ids;
        }

        private string GetIdxs()
        {
            string idxs = "";
            foreach (int rowHandle in bgvKst.GetSelectedRows())
            {
                if (rowHandle > -1)
                {
                    string idx = bgvKst.GetRowCellValue(rowHandle, "idx").ToString();

                    if (idx != "")
                        idxs += idx + ",";
                }
            }

            idxs = idxs.RemoveIfEndsWith(",");

            return idxs;
        }

        void KSip_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (KDept)
                if (ds.KST.GetChanges() != null)
                    if (XtraMessageBox.Show("Kaydetmek ister misiniz?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        btnKaydet.PerformClick();
        }

        void bgw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                DataTable d = (e.Result as DataSet).Tables[0];
                ds.KST.Merge(d);
            }
        }

        void bgw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            DateTime maxDate = new DateTime(2000, 1, 1);
            if (ds.KST.Rows.Count > 0)
                maxDate = (DateTime)ds.KST.Compute("MAX(ModifiedOn)", string.Empty);

            DataSet dsNew = Session.DataManager.ExecuteDataSet("GetK", maxDate);
            e.Result = dsNew;
        }

        void RefreshKst()
        {
            if (!bgvKst.IsEditing)
            {
                if (!isHandleDestroyed)
                    if (!bgw.IsBusy)
                        bgw.RunWorkerAsync();
            }
            //else
            //    Notify("Refresh pending. Press G! at your earliest convenience.");
        }

        void Exp(bool flag)
        {
            if (flag)
            {
                ds.KST.Columns["KalanMt"].Expression = "ISNULL(Mt,0) - ISNULL(DepoyaGelenMt,0)";
                ds.KST.Columns["LineTotal"].Expression = "DepoyaGelenMt * FaturaFiyati";
                ds.KST.Columns["EstTotal"].Expression = "YuklenenMt * ISNULL(FaturaFiyati, AnlasilanFiyat)";
                //ds.KST.Columns["Yukleme"].Expression = "Iif(ISNULL(GerYuklemeTarihi,ISNULL(RevYuklemeTarihi,OngYuklemeTarihi))-DATE()<4, ISNULL(GerYuklemeTarihi,ISNULL(RevYuklemeTarihi,OngYuklemeTarihi))-DATE(), null)";
                //ds.KST.Columns["Varis"].Expression = "Iif(DATEDIFF(dd,ETAVarisTarihi,GETDATE())<4, DATEDIFF(dd,ETAVarisTarihi,GETDATE()), null)";

            }
            else
                ds.KST.Columns["KalanMt"].Expression =
                ds.KST.Columns["EstTotal"].Expression =
                    //ds.KST.Columns["Yukleme"].Expression =
                    //ds.KST.Columns["Varis"].Expression =
                ds.KST.Columns["LineTotal"].Expression = null;
        }

        void btnKaydet_Click(object sender, EventArgs e)
        {
            if (!isHandleDestroyed)
                this.Invoke(new UpdateDataSourceDelegate(UpdateData));
        }



        DataTable dtY;
        void UpdateData()
        {
            try
            {
                //timerD.Stop();

                //foreach (MyData.KSTRow x in ds.KST.Select("idx is null"))
                //    ds.KST.RemoveKSTRow(x);

                btnKaydet.Enabled = false;

                DateTime maxDate = new DateTime(2000, 1, 1);
                if (ds.KST.Rows.Count > 0)
                    maxDate = (DateTime)ds.KST.Compute("MAX(ModifiedOn)", string.Empty);

                Exp(false);
                Save();


                int UreticiId = GetVal("UreticiId").ToInt();
                if (UreticiId > 0)
                    if (btnYukleme.Checked)
                    {
                        dtY.Clear();

                        foreach (DataRow r in ds.KST.Rows)
                            if (r["SonYukleme"].ToDecimal() > 0)
                                dtY.Rows.Add(r["idx"].ToInt(), r["SonYukleme"].ToDecimal(), 0);

                        if (dtY.Rows.Count > 0)
                            using (KstYukleme ky = new KstYukleme(UreticiId, dtY.Serialize()))
                                if (ky.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                    btnYukleme.Checked = false;
                    }

                if (btnSatirBol.Checked)
                {
                    dtY.Clear();

                    foreach (DataRow r in ds.KST.Rows)
                        if (r["BolunecekMt"].ToDecimal() > 0)
                            dtY.Rows.Add(r["idx"].ToInt(), 0, r["BolunecekMt"].ToDecimal());

                    if (dtY.Rows.Count > 0)
                        using (SatirBol ky = new SatirBol(AyrimIds, dtY.Serialize()))
                            if (ky.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                AyrimIds = ky.AyrimIds;
                                btnSatirBol.Checked = false;
                            }
                }

                ExecuteNonQuery("UpdK2", maxDate, (KDept ? WhoAmI : 0));
                DetayAl(maxDate);


                Exp(true);
                Notify("KST updated.");
                ds.KST.AcceptChanges();

                //if (ds.KST.Select("S is not null", "").Length > 0)
                //    XtraMessageBox.Show(Environment.NewLine + "Toplam " + ds.KST.Select("S is not null", "").Length.ToString() + " satır, başkaları tarafından değiştirildiği için saklanamadı! Tekrar kaydetmeyi deneyin." + Environment.NewLine, "CONFLICT detected!", MessageBoxButtons.OK);
            }
            catch (ApplicationException aex)
            {
                ShowInfoMessage(aex.Message);
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                btnKaydet.Enabled = true;
                //timerD.Start();
            }
        }
        //int AyrimId = 0;
        List<int> AyrimIds = new List<int>();

        void bgvKst_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            bool fix = false;
            DataRow dr = bgvKst.GetFocusedDataRow();
            if (dr != null)
                if (bgvKst.FocusedColumn.FieldName == "YuklenenMt")
                    fix = dr["YuklemeId"].ToInt() == 0 && dr["GerYuklemeTarihi"] == DBNull.Value;
                else if (bgvKst.FocusedColumn.FieldName == "SonYukleme")
                    fix = dr["YuklenenMt"].ToInt() > 0;

            e.Cancel = fix;

            //e.Cancel =AmI(1, 82) &&
            //    ";BelgeNo;FaturaTarihi;GerDepoVarisTarihi;DepoyaGelenMt;Durum2Id;OrderRef;Notlar;".IndexOf(";" + bgvKst.FocusedColumn.FieldName + ";") < 0;
        }

        void Upd(pages pageNr, string txt)
        {
            Expl[(int)pageNr] = txt;
            txtInfo.Caption = Expl[tabAna.SelectedTabPageIndex];
        }

        void KST_HandleDestroyed(object sender, EventArgs e)
        {
            isHandleDestroyed = true;
        }

        void gv_ShowFilterPopupCheckedListBox(object sender, FilterPopupCheckedListBoxEventArgs e)
        {
            GridView view = ((GridView)sender);

            // Show the "Select All" item.
            e.CheckedComboBox.SelectAllItemVisible = true;

            e.CheckedComboBox.BeginUpdate();
            object[] obj = view.DataController.FilterHelper.GetUniqueColumnValues(e.Column.ColumnHandle, -1, false, true, null);
            if (obj != null)
                for (int i = e.CheckedComboBox.Items.Count - 1; i >= 0; i--)
                    if (Array.IndexOf(obj, ((DevExpress.XtraGrid.Views.Grid.FilterItem)e.CheckedComboBox.Items[i].Value).Value) == -1)
                        e.CheckedComboBox.Items.RemoveAt(i);

            e.CheckedComboBox.EndUpdate();
        }

        void TabControl_DoubleClick(object sender, EventArgs e)
        {
            XtraTabControl tabControl = (sender as XtraTabControl);
            XtraTabHitInfo info = tabControl.CalcHitInfo(tabControl.PointToClient(Cursor.Position));
            if (info.HitTest == XtraTabHitTest.PageHeader)
            {
                XtraTabPage page = info.Page;
                switch (page.Name)
                {
                    case "tpListe":
                        RefreshKst();
                        break;
                    //case "tpOzet":
                    //    RefreshOzet();
                    //    break;
                }
            }
        }

        void KSip_DoubleClick(object sender, EventArgs e)
        {
            FuzzySearch fs;

            if (bgvKst.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                fs = new FuzzySearch(strParse(bsKST, "StokKodu"));
            else
                fs = new FuzzySearch();

            if (fs.ShowDialog() == DialogResult.OK)
            {
                if (bgvKst.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                    bgvKst.SetFocusedRowCellValue("ProductId", fs.ProductId);
                else
                {
                    MyData.KSTRow r = ds.KST.NewKSTRow();
                    r.ProductId = fs.ProductId;
                    ds.KST.AddKSTRow(r);
                }
                bgvKst.EndEditing();
                bgvKst.RefreshData();
            }
        }


        void btnSatirEkle_Click(object sender, EventArgs e)
        {
            using (KEkle kstekle = new KEkle(strParse(bsKST, "SipNo")))
            {
                if (kstekle.ShowDialog() == DialogResult.OK)
                {
                    RefreshKst();
                    SipNo = kstekle.SipNo;

                    barManager.Items["Siparişin tamamı"].PerformClick();
                    //cmbGoster.SelectedIndex = 3;
                }
            }
        }

        void pgcAyrim_CellSelectionChanged(object sender, EventArgs e)
        {
            double PivotSum = 0.0;
            foreach (Point cell in pgcAyrim.Cells.MultiSelection.SelectedCells)
            {
                PivotCellEventArgs cellInfo = pgcAyrim.Cells.GetCellInfo(cell.X, cell.Y);
                if (cellInfo.ColumnValueType == PivotGridValueType.Value &&
                    cellInfo.RowValueType == PivotGridValueType.Value)
                    PivotSum += Convert.ToDouble(pgcAyrim.GetCellValue(cell.X, cell.Y));
            }

            lblPivotSum.Text = PivotSum == 0 ? string.Empty : String.Format("{0:#,##0.## mt'.'}", PivotSum);
        }

        void pgc_CellClick(object sender, PivotCellEventArgs e)
        {
            PivotGridControl pg = (PivotGridControl)sender;
            GridControl gc = pg.Name == "pgcRapor" ? gridControl1 : gridControl2;
            gc.DataSource = e.CreateDrillDownDataSource();
            GridView gv = (GridView)gc.MainView;

            ExpandCollapse(pg.Name == "pgcRapor" ? scc1 : scc4, (gv.RowCount > 0 ? AcKapa.Expand : AcKapa.Collapse));

            gv.OptionsView.ColumnAutoWidth = false;
            gv.BestFitColumns();
            //gv.Columns["Mt"].Width = 100;
        }

        void gleSiparis_EditValueChanged(object sender, EventArgs e)
        {
            if (gleSiparis.EditValue != null)
            {
                Upd(pages.Raporlama, "- KST: " + gleSiparis.Properties.View.GetFocusedDataRow()["PO#"].ToString());
                bsKSTpvt.Filter = "SipNo2 = '" + gleSiparis.EditValue.ToString() + "'";
                //pgcAyrim.BestFit();
            }
        }

        void FillAyrimTables()
        {
            ds.xKstSip.Clear();
            GetDetails("xKstSip", "GetKstAyrim2");
            RepositoryItemGridLookUpEdit riSip = GetCustomGLE(ds.xKstSip, "PO#", "PO#");
            gleSiparis.Properties.Assign(riSip);
            gleSiparis.Properties.View.Columns["SipNo"].Visible = false;
            bsKSTpvt.Filter = string.Empty;
            Notify("xKstSip refreshed.");
        }

        void teLayout_EditValueChanged(object sender, EventArgs e)
        {
            btnSaveLayout.Enabled = (teLayout.Text != string.Empty);
        }

        void leLayout_EditValueChanged(object sender, EventArgs e)
        {
            pgcRapor.RestoreLayoutFromStream(StringToMemoryStream(ds.SavedLayouts.FindByUserIdControlIdLayoutName(WhoAmI, 1, leLayout.Text).LayoutXML));
            Upd(pages.Raporlama, "- KST" + (tabAna.SelectedTabPage == tpAnaliz ? ". " + leLayout.EditValue : ""));
        }

        void bgvKST_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            int[] rows = bgvKst.GetSelectedRows();
            if (rows.Length == 0)
                return;

            decimal toplamfiyat = 0;
            string doviz = string.Empty;

            try
            {
                foreach (int rowHandle in rows)
                {
                    decimal qty = GetDecimal(bgvKst.GetRowCellValue(rowHandle, "Mt"));
                    decimal fiyat = GetDecimal(bgvKst.GetRowCellValue(rowHandle, "AnlasilanFiyat"));

                    if (qty != -1 && fiyat != -1)
                    {
                        toplamfiyat += qty * fiyat;
                        doviz = bgvKst.GetRowCellDisplayText(rowHandle, "DvzId");
                    }
                }
            }
            catch (Exception Ex)
            {
                Notify(Ex.Message);
            }

            if (toplamfiyat > 0)
                SelectionInfo = String.Format("Toplam Fiyat: {0:n2} {1}", toplamfiyat, doviz);
            else
                SelectionInfo = "";
        }

        decimal GetDecimal(object value)
        {
            decimal result = -1;

            if (value == DBNull.Value)
            {
            }
            else if (value == null)
            {
            }
            else
            {
                try
                {
                    result = Convert.ToDecimal(value, Application.CurrentCulture);
                }
                catch
                {

                }
            }
            return result;
        }
        /*
        void gvOzet_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            string info = "";
            int adet = 0;
            float siparis = .0f, gelen = .0f;
            try
            {
                foreach (int rowHandle in gvKstOzet.GetSelectedRows())
                {
                    if (gvKstOzet.GetRowCellValue(rowHandle, "SiparisEdilenMiktar") != DBNull.Value)
                        siparis += float.Parse(gvKstOzet.GetRowCellValue(rowHandle, "SiparisEdilenMiktar").ToString());

                    if (gvKstOzet.GetRowCellValue(rowHandle, "GelenMiktar") != DBNull.Value)
                        gelen += float.Parse(gvKstOzet.GetRowCellValue(rowHandle, "GelenMiktar").ToString());

                    adet++;
                }
            }
            catch (Exception Ex)
            {
                Notify(Ex.Message);
            }
            finally
            {
                info = siparis == 0 ? string.Empty : String.Format("Sipariş edilen: {0:#,##0.## mt'.'} | Gelen: {1:#,##0.## mt'.'} | {2:#} satır", siparis, gelen, adet);
                //teSiparisGelen.Text = info;
            }

            SelectionInfo = info;
        }
        */
        void RefreshFilter()
        {
            try
            {
                bgvKst.BeginSort();
                switch (Kapsam)
                {
                    case "Çağrılan satır":
                        bsKST.Filter = "SipNo = '" + SipNo + "'" +
                            (_BrandId > 0 ? " AND BrandId = " + _BrandId.ToString() : "") +
                            (_UreticiId > 0 ? " AND UreticiId = " + _UreticiId.ToString() : "") +
                            (_SipVerenId > 0 ? " AND SipVerenId = " + _SipVerenId.ToString() : "") +
                            (_SezonId > 0 ? " AND SezonId = " + _SezonId : " AND SezonId is null") +
                            (_OrderRef != string.Empty ? " AND OrderRef = '" + _OrderRef + "'" : " AND OrderRef is null") +
                            (_ETA > new DateTime(1, 1, 1) ? " AND ETAVarisTarihi = '" + _ETA.ToShortDateString() + "'" : " AND ETAVarisTarihi is null");
                        //(_ETD > new DateTime(1, 1, 1) ? " AND ETDYuklemeTarihi = '" + _ETD.ToShortDateString() + "'" : " AND ETDYuklemeTarihi is null");

                        bgvKstBestFitColumns();
                        break;
                    case "O markaya ait satırlar":
                        bsKST.Filter = "SipNo = '" + SipNo + "'" +
                            (_BrandId > 0 ? " AND BrandId = " + _BrandId.ToString() : "");
                        bgvKstBestFitColumns();
                        break;
                    case "O üreticiye ait satırlar":
                        bsKST.Filter = "SipNo = '" + SipNo + "'" +
                            (_UreticiId > 0 ? " AND UreticiId = " + _UreticiId.ToString() : "");
                        bgvKstBestFitColumns();
                        break;
                    case "Siparişin tamamı":
                        bsKST.Filter = "SipNo = '" + SipNo + "'";
                        bgvKstBestFitColumns();
                        break;
                    case "Bütün siparişler":
                        bsKST.Filter = string.Empty;
                        Upd(pages.DetayListe, "- KST");
                        bgvKstBestFitColumns();
                        break;
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
            finally
            {
                bgvKst.EndSort();
            }
        }

        void barManager_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                switch (e.Item.Caption)
                {
                    case "Çağrılan satır":
                    case "O markaya ait satırlar":
                    case "O üreticiye ait satırlar":
                    case "Siparişin tamamı":
                    case "Bütün siparişler":
                        Kapsam = e.Item.Caption;
                        RefreshFilter();
                        break;

                    default:
                        if (e.Item.Tag != null)
                        {
                            if (e.Item.Tag.ToString()[0] == 'C')
                            {
                                //bsKST.Filter = (e.Item.Tag.ToString() == "C0" ? e.Item.Tag.ToString() + "=1" : "");
                                bsKST.Filter = e.Item.Tag.ToString() + "=1";
                                Upd(pages.DetayListe, "- KST. " + warnings[int.Parse(e.Item.Tag.ToString().Substring(1))]);
                                //e.Item.Tag.ToString() != "C0" ? warningsCnt[int.Parse(e.Item.Tag.ToString().Substring(1))].ToString() : "";
                            }
                            QuickJump(e.Item.Tag.ToString());
                        }
                        break;
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        void bgvKstBestFitColumns()
        {
            bgvKst.BestFitColumns();
            //bgvKst.Columns["Mt"].BestFit();
            foreach (string str in "xTerminAciklama;xMiktarAciklama;xFiyatAciklama".Split(';'))
                bgvKst.Columns[str].Width = 300;

        }

        void QuickJump(string Nr)
        {
            int cnt = 0;
            /*if (Nr[0] == 'C')
            {
                switch (int.Parse(Nr.Substring(1)))
                {
                    case 1:
                    case 2:
                        cnt = 7; break;
                    case 3:
                        cnt = 8; break;
                    case 4:
                        cnt = 9; break;
                    case 5:
                        cnt = 5; break;
                }
            }
            else*/
            int.TryParse(Nr, out cnt);


            //bgvKst.Bands[0].Visible = true;
            if (cnt == 0)
            {
                for (int i = 0; i < bgvKst.Bands.Count; i++)
                    bgvKst.Bands[i].Visible = i < 6 || cnt - 1 == i;
                BandedGridViewInfo vi = bgvKst.GetViewInfo() as BandedGridViewInfo;
                int bandNr = cnt - 1 > 0 ? cnt - 1 : 0;
                bgvKst.LeftCoord = vi.GetColumnLeftCoord(bgvKst.Bands[bandNr].Columns[0]) - bgvKst.Bands[0].Width;

            }
            else
            {
                for (int i = 0; i < bgvKst.Bands.Count; i++)
                    bgvKst.Bands[i].Visible = (cnt - 1 == i);
                //bgvKst.Bands[5].Visible = false;
            }
        }

        //void gvKstOzet_DoubleClick(object sender, EventArgs e)
        //{
        //    //ExcelEnabled = false;
        //    //gvArtikel.OptionsView.NewItemRowPosition = gvAyrim.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
        //    //if (view.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
        //    GridView view = ((GridView)sender);
        //    GridHitInfo hi = view.CalcHitInfo(view.GridControl.PointToClient(MousePosition));
        //    if (hi.InRow || hi.InRowCell)
        //    {
        //        if (bsKstOzet.Current != null)
        //        {
        //            DataRow curr = ((DataRowView)bsKstOzet.Current).Row;
        //            SipNo = curr["SipNo"].ToString();
        //            _BrandId = intParse(bsKstOzet, "BrandId");
        //            _UreticiId = intParse(bsKstOzet, "UreticiId");
        //            _SipVerenId = intParse(bsKstOzet, "SiparisEdenId");
        //            _SezonId = intParse(bsKstOzet, "SezonId");  //curr["SezonId"].ToString();
        //            _OrderRef = curr["OrderRef"].ToString();
        //            _ETA = datetimeParse(bsKstOzet, "ETAVarisTarihi");
        //            //_ETD = datetimeParse(bsKstOzet, "ETDYuklemeTarihi");

        //            Upd(pages.DetayListe, "- KST. " + SipNo);
        //            barManager.Items["Çağrılan satır"].PerformClick();
        //            bgvKstBestFitColumns();
        //            tabAna.SelectedTabPage = tpListe;
        //        }
        //        else
        //            Upd(pages.DetayListe, "- KST");
        //    }
        //}

        void tabAna_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            //panelControl5.Visible = ExcelEnabled = (tabAna.SelectedTabPage == tpListe);
            txtInfo.Caption = Expl[tabAna.SelectedTabPageIndex];
        }

        void PrepareImageComboBoxEdit(GridView gv, string colName, string opts)
        {
            RepositoryItemImageComboBox imageCombo = gv.GridControl.RepositoryItems.Add("ImageComboBoxEdit") as RepositoryItemImageComboBox;
            imageCombo.Items.BeginUpdate();
            int ndx = 0;
            imageCombo.SmallImages = noktalar;

            foreach (string opt in opts.Split('|'))
                imageCombo.Items.Add(new ImageComboBoxItem(opt, ndx++));
            //imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Default;
            imageCombo.Items.EndUpdate();
            gv.Columns[colName].ColumnEdit = imageCombo;
        }

        RepositoryItemComboBox RiKapsam;
        void PrepareRiKapsam()
        {
            //gvModel.Columns["Linea"].ColumnEdit = riLinea;

            RiKapsam = new RepositoryItemComboBox();
            RiKapsam.Items.AddRange(new object[] { "Son 1 yıl", "Tümü" });
            RiKapsam.TextEditStyle = TextEditStyles.DisableTextEditor;
        }

        void InitPivot(PivotGridControl pgc)
        {
            pgc.OptionsCustomization.CustomizationFormStyle = DevExpress.XtraPivotGrid.Customization.CustomizationFormStyle.Excel2007;
            pgc.DataSource = bsKSTpvt;
            pgc.CellClick += new PivotCellEventHandler(pgc_CellClick);
            pgc.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pivotGrid_FieldValueDisplayText);
            pgc.BeginUpdate();
            pgc.RetrieveFields();

            foreach (PivotGridField f in pgc.Fields)
            {
                f.Name = "_" + f.FieldName;
                f.Visible = false;
                switch (f.FieldName)
                {
                    case "BrandId": f.FieldEdit = RI(Rp.Brand); break;
                    case "UreticiId": f.FieldEdit = RI(Rp.V_VendorK); break; //KVendor
                    case "SipVerenId": f.FieldEdit = RI(Rp.V_User); break;
                    case "DvzId":
                    case "FaturaDvzId": f.FieldEdit = RI(Rp.Currency); break;
                    case "KaliteId": f.FieldEdit = RI(Rp.Kalite); break;
                    //OA: KaliteId ler değişti!
                    case "TeslimSekliId":
                    case "TeslimSekliAId": f.FieldEdit = RI(Rp.TeslimSekliA); break;
                    case "OngShipMethodId": f.FieldEdit = RI(Rp.ShipMethod); break;
                    case "SezonId": f.FieldEdit = RI(Rp.Sezon); break;
                    case "OrderRef":
                    case "Kalite":
                    case "SipNo":
                    case "SipNo2":
                    case "Mt":
                    case "YuklenenMt":
                    case "StokKodu":
                    case "SipTarihi":
                    case "DepoVarisTarihi":
                    case "KaliteAciklama":
                    case "DepoyaGelenMt":
                    case "AnlasilanFiyat":
                    case "FaturaFiyati":
                    case "KalanMt":
                    case "YuklemeTarihi":
                    case "OngYuklemeTarihi":
                    case "Durum":
                        break;

                    //Yükleme termini
                    //new field - toplam tutar  (metre x fiyat+dvz cinsi)
                    default:
                        f.Options.ShowInCustomizationForm = false;
                        //BU SATIR, İSTEMEDİĞİMİZ SÜTUNLARI SİLMEDİ
                        //pgc.Fields.RemoveAt(i);
                        break;
                }
            }

            if (pgc.Name == "pgcRapor")
                AddNewField(pgc, "Mt", PivotArea.DataArea).SummaryType = DevExpress.Data.PivotGrid.PivotSummaryType.Sum;
            else if (pgc.Name == "pgcAyrim")
            {
                AddNewField(pgc, "StokKodu", PivotArea.RowArea);
                AddNewField(pgc, "BrandId", PivotArea.ColumnArea).FieldEdit = RI(Rp.Brand);
                AddNewField(pgc, "DepoyaGelenMt", PivotArea.DataArea).Visible = false;
                AddNewField(pgc, "Mt", PivotArea.DataArea).Visible = false;
                //AddNewField(pgc, "OngYuklemeTarihi", PivotArea.FilterArea);
                //PivotGridField[] fields = new PivotGridField[2];
                //fields[0] = AddNewField(pgc, "KarbelKaliteId", PivotArea.RowArea);
                //fields[0].FieldEdit = riKarbelKalite;
                //pgc.Groups.Add(fields, "KaliteDesenRenk");
            }

            foreach (PivotGridField pgf in pgc.Fields)
            {
                pgf.SortOrder = PivotSortOrder.Ascending;
                pgf.Options.AllowFilter = DevExpress.Utils.DefaultBoolean.True;
                pgf.Options.AllowSort = DevExpress.Utils.DefaultBoolean.True;
            }

            pgc.EndUpdate();
        }

        void bgvKST_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            BandedGridView gridView = sender as BandedGridView;

            if (e.RowHandle > -1)
                try
                {
                    switch (e.Column.FieldName)
                    {
                        case "!ProductId":
                            if (e.CellValue != null)
                                if (e.CellValue != DBNull.Value)
                                {
                                    object val = e.CellValue;

                                    if (e.RowHandle == gridView.FocusedRowHandle)
                                        e.Appearance.Font = new System.Drawing.Font(e.Appearance.Font, FontStyle.Bold);
                                    if (val == DBNull.Value)
                                        e.Appearance.BackColor = e.Appearance.BackColor2 = Color.SkyBlue;   // Color.FromArgb(255, 192, 0);
                                    else
                                        e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView.Appearance.EvenRow : gridView.Appearance.OddRow);
                                }
                            break;


                        case "Varis":
                        case "Yukleme":
                            bool var = false;
                            if (e.CellValue != null)

                                if (e.CellValue != DBNull.Value)
                                    var = true;

                            if (var)
                            {
                                e.Appearance.Font = new System.Drawing.Font(e.Appearance.Font, FontStyle.Bold);
                                e.Appearance.BackColor = Color.Gold;
                            }
                            else
                                if (!gridView.OptionsView.AllowCellMerge)
                                    if (e.RowHandle % 2 == 0 /*&& e.Appearance.BackColor == Color.White*/)
                                        if (((BandedGridColumn)e.Column).OwnerBand != null)
                                        {
                                            int index = ((BandedGridColumn)e.Column).OwnerBand.Index;
                                            e.Appearance.BackColor = colors[index];
                                        }

                            break;

                        default:
                            if (!gridView.OptionsView.AllowCellMerge)
                            {
                                if (e.Column.FieldName == "SonYukleme" && btnYukleme.Checked)
                                    e.Appearance.BackColor = Color.LightBlue;

                                else if (e.Column.FieldName == "BolunecekMt" && btnSatirBol.Checked)
                                    e.Appearance.BackColor = Color.Khaki;

                                else if (e.RowHandle % 2 == 0 /*&& e.Appearance.BackColor == Color.White*/)
                                    if (((BandedGridColumn)e.Column).OwnerBand != null)
                                    {
                                        int index = ((BandedGridColumn)e.Column).OwnerBand.Index;
                                        e.Appearance.BackColor = colors[index];
                                    }
                            }
                            break;
                    }
                }
                catch
                {
                }
        }

        //gvKstOzet.MakeRowVisible(gvKstOzet.LocateByValue(0, gvKstOzet.Columns["SipNo"], Current), true);

        void bgvKst_RowStyle(object sender, RowStyleEventArgs e)
        {
            switch (intParse(bgvKst.GetRowCellValue(e.RowHandle, "Durum1Id")))
            {
                case 3:
                    e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Strikeout);
                    e.Appearance.ForeColor = Color.FromName(AppSession.Settings.KstColor1); // SystemColors.ControlDark;
                    break;
                case 2:
                    e.Appearance.ForeColor = Color.FromName(AppSession.Settings.KstColor1);
                    break;
            }

            if (bgvKst.GetRowCellValue(e.RowHandle, "SipTarihi") == DBNull.Value)
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        void ExceldenTopluGiris()
        {
            try
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string FileName = ofd.FileName;
                    //ExecQuery("ImportPO", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)).ToString(), SipNo, 1, 3, WhoAmI, Application.CurrentCulture.ToString());
                    RefreshKst();
                }
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
        }

        void btnSaveLayout_Click(object sender, EventArgs e)
        {
            MemoryStream stream = new MemoryStream();
            pgcRapor.SaveLayoutToStream(stream, OptionsLayoutBase.FullLayout);

            //Please use the SaveLayoutToRegistry method as follows:
            //test.SaveLayoutToRegistry("SaveToRegistryRestoreFieldCountTest", OptionsLayoutBase.FullLayout);

            string ly = MemoryStreamToString(stream);
            ds.SavedLayouts.AddSavedLayoutsRow(WhoAmI, 1, teLayout.Text, ly, null, DateTime.Now);

            ExecuteNonQuery("UpdLayouts", ds.SavedLayouts.SerializeChanges());
            ds.SavedLayouts.AcceptChanges();
        }

        void btnDeleteLayout_Click(object sender, EventArgs e)
        {
            ExecuteNonQuery("DeleteLayout", WhoAmI, 1, leLayout.Text);
            ds.SavedLayouts.FindByUserIdControlIdLayoutName(WhoAmI, 1, leLayout.Text).Delete();
            ds.SavedLayouts.AcceptChanges();
        }

        void btnYazdir_Click(object sender, EventArgs e)
        {
            AyrimFoyu ayrimFoyu = new AyrimFoyu();
            ayrimFoyu.pivotContainer.WinControl = pgcRapor;
            ayrimFoyu.ShowPreview();
        }

        void UKMK(object sender, EventArgs e)
        {
            if (intParse(bsKST, "ProductId") > 0)
                using (Kodlar kodlar = new Kodlar(intParse(bsKST, "ProductId")))
                {
                    kodlar.ShowDialog();
                    /*
                    if (pol.ShowDialog() == DialogResult.OK)  
                    {
                        gvGPLines.SetFocusedRowCellValue("VendorId", pol.VendorId);
                        gvGPLines.SetFocusedRowCellValue("UreticiKodu", pol.UreticiKodu);
                    }
                     */
                }
        }

        BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        //object GetValM(string FieldName)
        //{
        //    return (vgc.Rows[1] as MultiEditorRow).PropertiesCollection[FieldName].Value;
        //}

        void btnGetir_Click(object sender, EventArgs e)
        {
            //FilterChanged();
            ds.KST.Clear();

            DetayAl(new DateTime(2000, 1, 1));

            //gvCELines.FocusedRowHandle = gvCELines.LocateByDisplayText(0, gvCELines.Columns["Hit"], "1");
            //gvCELines2.FocusedRowHandle = gvCELines2.LocateByDisplayText(0, gvCELines2.Columns["Hit"], "1");

            //barManager.Items["Bütün siparişler"].PerformClick();

            btnYukleme.Enabled = intParse(GetVal("UreticiId")) > 0;

            bgvKst.BestFitColumns();
            tabAna.SelectedTabPage = tpListe;

            Notify("Done.");
        }

        private void DetayAl(DateTime ModifiedOn)
        {
            GetDetails("KST", "GetKstFiltered6",
                strParse(GetVal("Kapsam")),
                strParse(GetVal("Durum")),
                boolParse(GetVal("Siparişin Tamamı")),
                intParse(GetVal("idx")),
                intParse(GetVal("Durum2Id")),
                intParse(GetVal("SipVerenId")),
                strParse(GetVal("PO#")),
                intParse(GetVal("BrandId")),
                intParse(GetVal("SezonId")),
                strParse(GetVal("OrderRef")),
                strParse(GetVal("KOD")),
                intParse(GetVal("ProductId")),
                intParse(GetVal("KaliteId")),
                intParse(GetVal("KompozisyonId")),
                strParse(GetVal("Konstruksiyon")),
                intParse(GetVal("FinishId")),
                intParse(GetVal("KstCategoryId")),
                intParse(GetVal("Mt")),
                datetimeParse(GetVal("FaturaTarihi")),
                strParse(GetVal("BelgeNo")),
                intParse(GetVal("DepoyaGelenMt")),
                datetimeParse(GetVal("SipTarihi")),
                strParse(GetVal("UreticiSipNo")),
                intParse(GetVal("UreticiId")),
                strParse(GetVal("UreticiKodu")),
                strParse(GetVal("KaliteAciklama")),
                strParse(GetVal("HLNo")),
                strParse(GetVal("Notlar")),
                ModifiedOn
                );
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);

            vgc.SetCellValue(vgc.Rows["Kapsam"], 0, "Son 1 yıl");
            vgc.SetCellValue(vgc.Rows["Durum"], 0, "AÇIK");

            //(vgc.Rows[1] as MultiEditorRow).PropertiesCollection["Aktif"].Value = true;
        }

        void CreateVerticalGrid()
        {
            vgc.Rows.AddRange(new BaseRow[] {            
                AddItem("Kapsam", typeof(string), RiKapsam),
                AddItem("Durum", typeof(string), riGenel),
                AddItem("Siparişin Tamamı", typeof(bool)),
                AddItem("idx", typeof(int)),
                AddItem("Durum2Id", typeof(int), RI(Rp.SiparisDurumu2)),
                AddItem("SipVerenId", typeof(int), RI(Rp.V_User)),
                AddItem("PO#", typeof(string)),
                AddItem("BrandId", typeof(int), RI(Rp.Brand)),
                AddItem("SezonId", typeof(int), RI(Rp.Sezon)),
                AddItem("OrderRef", typeof(string)),
                AddItem("KOD", typeof(string)),
                AddItem("ProductId", typeof(int), RI(Rp.V_Kumas)),
                AddItem("KaliteId", typeof(int), RI(Rp.Kalite)),
                AddItem("KompozisyonId", typeof(int), RI(Rp.Kompozisyon)),
                AddItem("Konstruksiyon", typeof(string)),
                AddItem("FinishId", typeof(int), RI(Rp.Finish)),
                AddItem("KstCategoryId", typeof(int), RI(Rp.KstCategory)),
                AddItem("Mt", typeof(int), new RepositoryItemCalcEdit()),
                AddItem("FaturaTarihi", typeof(DateTime)),
                AddItem("BelgeNo", typeof(string)),
                AddItem("DepoyaGelenMt", typeof(int), new RepositoryItemCalcEdit()),
                AddItem("SipTarihi", typeof(DateTime)),
                AddItem("UreticiSipNo", typeof(string)),
                AddItem("UreticiId", typeof(int), RI(Rp.V_VendorK)),
                AddItem("UreticiKodu", typeof(string)),
                AddItem("KaliteAciklama", typeof(string)),
                AddItem("HLNo", typeof(string)),
                AddItem("Notlar", typeof(string))
            });

            vgc.GetRowByFieldName("Notlar").Height = 60;
            vgc.SetCellValue(vgc.Rows["Kapsam"], 0, "Son 1 yıl");

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += new CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            //vgc.RecordWidth = splitContainerControl2.Panel1.Width - vgc.RowHeaderWidth - 3;

            vgc.SetCellValue(vgc.Rows["Durum"], 0, "AÇIK");
            //(vgc.Rows[1] as MultiEditorRow).PropertiesCollection["Aktif"].Value = true;
            vgc.FocusedRow = vgc.Rows["SipNo2"];
            vgc.BestFit();
        }

        MultiEditorRow AddMultiItem(params MultiItemRp[] ms)
        {
            List<MultiEditorRowProperties> lst = new List<MultiEditorRowProperties>();
            foreach (MultiItemRp m in ms)
            {
                MultiEditorRowProperties row1 = new MultiEditorRowProperties();
                row1.Caption = row1.FieldName = m.Name;
                switch (m.Type.ToString())
                {
                    case "System.Boolean": row1.RowEdit = new RepositoryItemCheckEdit(); break;
                }
                lst.Add(row1);
            }

            MultiEditorRow row = new MultiEditorRow();
            row.PropertiesCollection.AddRange(lst.ToArray());
            row.Height = 20;
            //row.ChildRows.AddRange(lst.ToArray());
            return row;
        }

        class MultiItemRp
        {
            public string Name;
            public Type Type;
            public MultiItemRp(string name, Type type)
            {
                Name = name;
                Type = type;
            }
        }

        #region Eşleme

        void SKToUK_Click(object sender, EventArgs e)
        {
            SKToCol("UreticiKodu");
        }

        void SKToMK_Click(object sender, EventArgs e)
        {
            SKToCol("MusteriKodu");
        }

        void SKToCol(string TargetCol)
        {
            foreach (int i in bgvKst.GetSelectedRows())
            {
                DataRow dr = bgvKst.GetDataRow(i);
                string BaseCode = dr[TargetCol].ToStr();

                string SK = dr["StokKodu"].ToStr();

                if (BaseCode != "" && BaseCode != SK)
                {
                    DialogResult result = XtraMessageBox.Show(string.Format("Mevcut {2}:\t{0}\r\nYeni {2}:\t\t {1}\r\nÜzerine yazmak istiyor musunuz?", BaseCode, SK, TargetCol), "Uyarı", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.No)
                        continue;
                }

                bgvKst.SetRowCellValue(i, TargetCol, SK);
            }
        }

        void KartAra_Click(object sender, EventArgs e)
        {
            List<KodSihirbazi.Kod> kodlar = new List<KodSihirbazi.Kod>();
            foreach (int rowHandle in bgvKst.GetSelectedRows())
            {
                DataRow dr = bgvKst.GetDataRow(rowHandle);
                string MK = dr["MusteriKodu"].ToStr();
                string UK = dr["UreticiKodu"].ToStr();
                string SK = dr["StokKodu"].ToStr();

                if (dr["ProductId"] == DBNull.Value)
                {
                    KodSihirbazi.Kod kod = new KodSihirbazi.Kod();
                    int customerId = -1;
                    int brandId = dr["BrandId"].ToInt(-1);

                    if (brandId != -1)
                        customerId = AppSession.Lookups.Brand.FindByBrandId(brandId).CustomerId;

                    kod.CustomerId = customerId;
                    kod.MusteriKodu = dr["MusteriKodu"].ToStr();

                    kod.UreticiId = dr["UreticiId"].ToInt(-1);
                    kod.UreticiKodu = dr["UreticiKodu"].ToStr();
                    kod.KaliteId = dr["KaliteId"].ToInt(-1);
                    kod.KaliteAciklama = dr["KaliteAciklama"].ToStr();
                    kod.RowHandle = rowHandle;

                    if (kod.MusteriKodu != string.Empty || kod.UreticiKodu != string.Empty)
                        kodlar.Add(kod);
                }
            }

            if (kodlar.Count > 0)
            {
                using (KodSihirbazi ks = new KodSihirbazi(kodlar))
                    if (ks.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        foreach (KodSihirbazi.Kod kod in ks.Kodlar)
                        {
                            if (kod.ProductId > 0)
                                bgvKst.SetRowCellValue(kod.RowHandle, "ProductId", kod.ProductId);
                        }
                    }
            }
            else
                XtraMessageBox.Show("Seçtikleriniz içinde, üretici ve/veya müşteri kodu girilmiş ANCAK ProductId'si setlenmemiş satır yok.");
        }

        private void dockPanel1_Click(object sender, EventArgs e)
        {

        }



        //string dosyalar = "";

        //void AyrimSihirbazi_Click(object sender, EventArgs e)
        //{
        //    btnAS.Visible = true;
        //    btnClearAS.Visible = true;
        //    foreach (int rowHandle in bgvKst.GetSelectedRows())
        //    {
        //        DataRow dr = bgvKst.GetDataRow(rowHandle);
        //        if (dr["ProductId"] != DBNull.Value && dr["Mt"] != DBNull.Value)
        //        {
        //            dosyalar += dr["idx"].ToString() + ",";
        //        }
        //    }

        //    if (dosyalar != "")
        //    {
        //        DataTable dt = ExecDatatable("GetAyrimSihirbazi", dosyalar.RemoveIfEndsWith(","));

        //        //if (dr["ProductId"] != DBNull.Value && dr["Mt"] != DBNull.Value)
        //        //{
        //        //    decimal qty = (decimal)dr["Mt"];
        //        //    string OrderRef = dr["OrderRef"].ToStr();

        //        //    int BrandId = dr["BrandId"].ToInt(-1);
        //        //    string brand = "";
        //        //    if (BrandId > 0)
        //        //        brand = AppSession.Lookups.Brand.FindByBrandId(BrandId).Abbr;

        //        //    int SezonId = dr["SezonId"].ToInt(-1);
        //        //    string sezon = "";
        //        //    if (SezonId > 0)
        //        //        sezon = AppSession.Lookups.Sezon.FindBySezonId(SezonId).Name;

        //        //    //OrderRef = OrderRef + "." + brand + "." + sezon;

        //        //    dtAS.Rows.Add(dr["ProductId"].ToInt(-1), qty, OrderRef, BrandId, SezonId);
        //        //}

        //        if (sepet == null || sepet.IsDisposed)
        //        { 
        //            sepet = new AyrimSepeti();
        //            sepet.SepetiBosalt += sepet_SepetiBosalt;
        //        }

        //        sepet.Init(dt);

        //        int ilkAyrim = AppSession.MainForm.Location.Y;

        //        Point baseLoc = AppSession.MainForm.PointToScreen(Point.Empty);
        //        int x = baseLoc.X;
        //        int w = AppSession.MainForm.Width;

        //        Point basePanel = HeaderPanel.PointToScreen(Point.Empty); 

        //        sepet.Show();
        //        sepet.Location = new Point(x + w - sepet.Width - 50, basePanel.Y+30);
        //    }
        //    else
        //        XtraMessageBox.Show("Seçtikleriniz içinde, ProductId ve MT alanları dolu satır yok.");
        //}

        //void sepet_SepetiBosalt()
        //{
        //    dosyalar = "";
        //}



        #endregion

        #region Comments
        //public void MyRefreshX()
        //{
        //    DataTable d = Session.DataManager.ExecuteDs("GetK", new DateTime(2010, 1, 1)).Tables[0];
        //    ds.KST.Merge(d);
        //    ds.KST.AcceptChanges();
        //}

        //void RaiseUpdate(object sender, System.Timers.ElapsedEventArgs e)
        //{
        //    timerD.Enabled = false;
        //    MyRefresh();
        //    timerD.Enabled = true;
        //}

        //bsKST.EndEdit();
        //bgvKst.CloseEditor();
        //if(bgvKst.ActiveEditor.ContainsFocus)
        //bgvKst.RefreshEditor(true);
        #endregion
    }
}
